package org.ru.mse10.cvis.service;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.ru.mse10.cvis.constants.UserRole;
import org.ru.mse10.cvis.entity.cv.User;
import org.ru.mse10.cvis.util.CommonUtil;

/**
 * The Class SystemConfigService.
 */
@Startup
@Singleton
public class SystemConfigService {

	/** The entity manager. */
	@PersistenceContext
	private EntityManager entityManager;

	/**
	 * Inits the.
	 */
	@PostConstruct
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public void init() {

		checkInitialUser();
	}

	/**
	 * Check initial user.
	 */
	private void checkInitialUser() {
		Query initialUserQuery = entityManager
				.createQuery("from User where role = "
						+ UserRole.INITIAL.ordinal());

		@SuppressWarnings("unchecked")
		List<User> list = initialUserQuery.getResultList();
		if (CommonUtil.isEmpty(list)) {
			User initial = new User();
			initial.setRole(UserRole.INITIAL);
			initial.setEmail("cvis.initial.admin.user@cvis.net");
			initial.setPassword(CommonUtil.hashPassword("1Nitu$er"));
			entityManager.persist(initial);
		} else if (list.size() > 1) {
			// TODO: deal with this - there should be only one initial user
		}
	}
}
